package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.result.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/4/1 1:27
 */
@RestController
@RequestMapping("/api/order/orderInfo")
public class WeixinController {
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    //生成微信扫码支付的二维码
    @GetMapping("/weixin/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId){

        String codeUrl=weixinService.createNative(orderId);

        return R.ok().data("codeUrl",codeUrl);
    }
    @ApiOperation(value = "查询支付状态")
    @GetMapping("/weixin/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId ){
        Map<String, String> resultMap =weixinService.queryPayStatus(orderId);
        if (resultMap==null){
            return R.error().message("支付出错");
        }

        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            //支付成功
            //更改orderInfo的支付状态
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            orderInfo.setId(orderId);
            orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
            orderInfoService.updateById(orderInfo);
            //更改paymentInfo的支付状态和支付信息
            paymentInfoService.UpdatePaymentInfo(resultMap,orderInfo.getOutTradeNo());
            return R.ok().message("支付成功");
        }
        return R.ok().message("支付中");
    }
    //取消预约
    @GetMapping("/auth/cancelOrder/{orderId}")
    public R cancelOrder(@PathVariable("orderId") Long orderId){
        Boolean flag=weixinService.cancelOrder(orderId);
        return R.ok().data("flag",flag);
    }
}
